<?php

namespace backend\modules\actionlogs\models;

use Yii;
use backend\models\Admin;
use backend\modules\admin\models\User;

/**
 * This is the model class for table "{{%action_logs}}".
 *
 * @property int $id
 * @property string $info
 * @property string $message
 * @property string $log_date
 * @property int $uid
 * @property int $item_id
 * @property string $ip_address
 */
class ActionLogs extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%action_logs}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['info', 'message', 'ip_address'], 'required'],
            [['message'], 'string'],
            [['log_date'], 'safe'],
            [['uid', 'item_id'], 'integer'],
            [['info'], 'string', 'max' => 255],
            [['ip_address'], 'string', 'max' => 40],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('mod_actionlogs', 'ID'),
            'info' => Yii::t('mod_actionlogs', 'ACTION'),
            'message' => Yii::t('mod_actionlogs', 'MESSAGE'),
            'log_date' => Yii::t('mod_actionlogs', 'DATE'),
            'uid' => Yii::t('mod_actionlogs', 'UID'),
            'item_id' => Yii::t('mod_actionlogs', 'ITEM_ID'),
            'ip_address' => Yii::t('mod_actionlogs', 'IP_ADDRESS'),
        ];
    }

    /**
     * 添加操作日志
     * @param string $info 操作记录
     * @param array $message 操作信息数组
     * @param int $userId 会员ID
     */
    public function addLog($info, $message, $userId = null)
    {
        $this->setAttributes([
            'info' => $info,
            'message' => json_encode($message),
            'uid' => $userId ?? Yii::$app->user->identity->id,
            'log_date' => time(),
            'item_id' => isset($message['id']) ? (int)$message['id'] : 0,
            'ip_address' => Yii::$app->request->getUserIP()
        ]);
        $this->save();
    }
}
